package com.soft.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ruoxi
 * @create 2021-12-30 14:00
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String successname = (String) req.getSession().getAttribute("successname");

        String servletName = req.getRequestURI().substring(req.getRequestURI().lastIndexOf("/") + 1);

        if ("".equals(servletName) || servletName.contains("login")
                || "randomCode".equals(servletName)
                || servletName.contains("css")
                || servletName.contains("js")
                || servletName.contains("font")
                || servletName.contains("jpg")) {
            filterChain.doFilter(req, resp);
        } else {
            if (successname != null) {
                filterChain.doFilter(req, resp);
            } else {
                resp.sendRedirect(req.getContextPath() + "/login.jsp");
            }
        }
    }
}
